<template>
  <div class="page">
    <el-card>
      <el-row class="filter-container">
        <el-button
          type="primary"
          size="small"
          class="filter-item"
          style="margin-left: 10px;"
          @click="handleSave"
        >
          保存
        </el-button>
        <el-button
          type="primary"
          size="small"
          class="filter-item"
          @click="handleCancel"
        >
          返回
        </el-button>
      </el-row>
      <el-row>
        <el-form
          ref="form"
          :model="form"
          label-width="110px"
          label-position="left"
          size="small"
          style="width: 90%;"
          :rules="role === 'dandang' ? rules1 : rules2"
        >
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="资产类别" prop="zclb">
                <el-select v-model="form.zclb" style="width: 100%;"
                           @change="handleMcChange" :disabled="role !== 'dandang' || type === 'zy'"
                >
                  <el-option
                    v-for="item in zcDic"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="名称" prop="mc">
                <el-select v-model="form.mc" style="width: 100%;"
                           :disabled="role !== 'dandang' || type === 'zy'"
                >
                  <el-option
                    v-for="item in zclbDic"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="品牌" prop="kcid">
                <!-- <el-input v-model="form.pp" :disabled="role !== 'zhixing'" /> -->
                <el-select
                  v-model="form.kcid"
                  style="width: 100%;"
                  @change="handleAutoComplete"
                  :disabled="role !== 'zhixing'||this.ppDisabe"
                >
                  <el-option
                    v-for="item in wpDic"
                    :key="item.id"
                    :label="item.pp"
                    :value="item.id"
                  >
                    <span class="mc">{{ item.mc_label }}</span>
                    <span class="pp">品牌：{{ item.pp }}</span>
                    <span class="gg">规格型号：{{ item.ggxh }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="规格型号" prop="ggxh">
                <el-input v-model="form.ggxh" :disabled="role !== 'zhixing'||this.ppDisabe" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="出厂日期" prop="ccrq">
                <el-date-picker
                  v-model="form.ccrq"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                  :picker-options="pickerOptions"
                  :disabled="role !== 'zhixing'||this.ppDisabe"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="购买日期" prop="gmrq">
                <el-date-picker
                  v-model="form.gmrq"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                  :picker-options="pickerOptions"
                  @change="handleGmrqChange"
                  :disabled="role !== 'zhixing'||this.ppDisabe"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="已使用年限" prop="synx">
                <el-input v-model="form.synx" :disabled="role !== 'zhixing'||this.ppDisabe" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数量" prop="sl">
                <el-input v-model="form.sl" :disabled="role !== 'dandang' || type === 'zy'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="客人公司" prop="krgs">
                <el-input v-model="form.krgs" :disabled="role !== 'dandang'||this.htDisabe" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客人姓名" prop="krxm">
                <el-input v-model="form.krxm" :disabled="role !== 'dandang'||this.htDisabe" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房租" prop="fz">
                <el-input v-model="form.fz" :disabled="role !== 'dandang'||this.htDisabe" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="存放地点" prop="cfd">
                <el-select v-model="form.cfd" style="width: 100%;"
                           :disabled="role !== 'dandang'" @change="handleCfdChange"
                >
                  <el-option
                    v-for="item in cfDic"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="房间号" prop="fjh">
                <el-select v-model="form.fjh" style="width: 100%;" @change="handleGetHt"
                           :disabled="role !== 'dandang'"
                >
                  <el-option
                    v-for="item in fjhDic"
                    :key="item.key"
                    :label="item.label"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="第二担当" prop="dedd">
                <el-select v-model="form.dedd" style="width: 100%;"
                           :disabled="role !== 'dandang'||this.htDisabe"
                >
                  <el-option
                    v-for="item in ddDic"
                    :key="item.username"
                    :label="item.person.personName"
                    :value="item.username"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="合同开始时间" prop="htksrq">
                <el-date-picker
                  v-model="form.htksrq"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                  :disabled="role !== 'dandang'||this.htDisabe"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合同结束时间" prop="htjsrq">
                <el-date-picker
                  v-model="form.htjsrq"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%;"
                  :disabled="role !== 'dandang'||this.htDisabe"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="24">
              <el-form-item label="备注" prop="bz">
                <el-input type="textarea" :rows="5" v-model="form.bz"
                          :disabled="role !== 'dandang'"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import {
  save, getAssetsZj, getAssetsHt, updateZt,
} from '@/api/assets-zj';
import { updateZt as updateLbZt } from '@/api/assets-lb';
import { getList as getDicList } from '@/api/dic';
import { checkNumber } from '@/utils/form-rule';
import { findUserByRolecode } from '@/api/user';
import { getAllList, save as updateKc } from '@/api/assets-gl';

export default {
  name: 'AssetsZjEdit',
  data() {
    const validateDate = (rule, value, callback) => {
      if (this.form.htksrq && this.form.htjsrq) {
        if (rule.field === 'htksrq' && value > this.form.htjsrq) {
          callback('合同开始时间不能大于结束时间');
        }
        if (rule.field === 'htjsrq' && value < this.form.htksrq) {
          callback('合同结束时间不能小于开始时间');
        }
      }
      callback();
    };
    return {
      form: {
        pzh: null,
        mc: '',
        zclb: '',
        pp: '',
        ggxh: '',
        ccrq: '',
        gmrq: '',
        synx: '',
        sl: '',
        cfd: '',
        fjh: '',
        htqx: '',
        dwfzr: '',
        jbr: '',
        zdrq: '',
        zdr: '',
        zt: '01',
        ztrq: '',
        bz: '',
        krgs: '',
        krxm: '',
        fz: '',
        yybfzr: '',
        htksrq: '',
        htjsrq: '',
        kcid: '',
        dedd: '',
      },
      zcDic: [],
      cfDic: [],
      zclbDic: [],
      fjhDic: [],
      htDisabe: false,
      ppDisabe: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      rules1: {
        mc: [{ required: true, message: '不能为空', trigger: 'blur' }],
        zclb: [{ required: true, message: '不能为空', trigger: 'blur' }],
        cfd: [{ required: true, message: '不能为空', trigger: 'blur' }],
        fjh: [{ required: true, message: '不能为空', trigger: 'blur' }],
        fz: [{ required: true, message: '不能为空', trigger: 'blur' }],
        krxm: [{ required: true, message: '不能为空', trigger: 'blur' }],
        sl: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { validator: checkNumber, trigger: 'change' },
        ],
        htksrq: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { validator: validateDate, trigger: 'change' },
        ],
        htjsrq: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { validator: validateDate, trigger: 'change' },
        ],
      },
      rules2: {
        kcid: [{ required: true, message: '不能为空', trigger: 'blur' }],
        ggxh: [{ required: true, message: '不能为空', trigger: 'blur' }],
        ccrq: [{ required: true, message: '不能为空', trigger: 'blur' }],
        gmrq: [{ required: true, message: '不能为空', trigger: 'blur' }],
        synx: [{ required: true, message: '不能为空', trigger: 'blur' }],
      },
      type: '',
      ddDic: [],
      wpDic: [],
    };
  },
  async mounted() {
    const [zc, cf, dd, wp] = await Promise.all([this.getZcDic(), this.getCfDic(),
      this.getDdDic(), this.getWpDic()]);
    this.zcDic = zc.data;
    this.cfDic = cf.data;
    this.ddDic = dd.data;
    this.wpDic = wp.data.map(item => ({
      ...item,
      mc_label: this.zcDic.find(it => it.code === item.zclb).dicDetails
        .find(it => it.key === item.mc).label,
    }));
    this.form.pzh = this.$route.query.pzh;
    this.type = this.$route.query.type;
    this.getFormData();
  },
  computed: {
    role() {
      return this.$store.state.user.role.roleCode;
    },
  },
  watch: {
    'form.mc': function (val, oldVal) {
      if (oldVal === '') return;
      this.form.pp = '';
      this.form.ggxh = '';
      this.form.ccrq = '';
      this.form.gmrq = '';
      this.form.kcid = '';
      this.form.synx = '';
    },
  },
  methods: {
    getFormData() {
      if (this.form.pzh) {
        getAssetsZj({ pzh: this.form.pzh }).then(res => {
          if (res.code === 200) {
            this.wpDic = this.wpDic.filter(item => item.zclb === res.data.zclb
              && item.mc === res.data.mc
              && (item.zt === '1' || item.id === res.data.kcid));
            Object.keys(this.form).forEach(item => {
              this.form[item] = res.data[item];
            });
            this.zclbDic = this.zcDic.find(item => item.code === this.form.zclb).dicDetails;
            this.fjhDic = this.cfDic.find(item => item.code === this.form.cfd).dicDetails;
            if (res.data.pp) {
              this.ppDisabe = true;
            } else {
              this.ppDisabe = false;
            }
          }
        });
      } else if (this.type === 'zy') {
        const data = this.$route.query.data;
        this.zclbDic = this.zcDic.find(item => item.code === data.zclb).dicDetails;
        this.form.mc = data.mc;
        this.form.zclb = data.zclb;
        this.form.pp = data.pp;
        this.form.ggxh = data.ggxh;
        this.form.ccrq = data.ccrq;
        this.form.gmrq = data.gmrq;
        this.form.sl = data.sl;
        this.form.kcid = data.kcid;
        this.handleGmrqChange(this.form.gmrq);
      }
    },
    handleSave() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const loadingInstance = this.$loading({ text: '正在保存...' });
          if (this.role === 'zhixing') {
            loadingInstance.close();
            const params = {
              id: this.form.kcid,
              zt: '3',
              ztrq: this.$dayjs().format('YYYY-MM-DD HH:mm:ss'),
            };
            const res = await updateKc(params);
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
          save(this.form).then(res => {
            loadingInstance.close();
            if (res.code === 200) {
              this.form.pzh = res.data.pzh;
              this.$message.success(res.message);
              if (this.role === 'zhixing') {
                this.handleUpdateZt(this.form.pzh, '02');
              }
              if (this.type === 'zy') {
                this.handleUpdateZt(this.$route.query.data.pzh, '03');
              }
              this.handleCancel();
            }
          });
        }
      });
    },
    handleUpdateZt(pzh, zt) {
      if (this.$route.query.ly === 'lb') {
        updateLbZt({ pzh, zt });
      } else {
        updateZt({ pzh, zt });
      }
    },
    handleCancel() {
      this.$router.go(-1);
    },
    handleMcChange(val) {
      this.form.mc = '';
      this.zclbDic = this.zcDic.find(item => item.code === val).dicDetails;
    },
    handleCfdChange(val) {
      this.form.fjh = '';
      this.fjhDic = this.cfDic.find(item => item.code === val).dicDetails;
    },
    handleGetHt(val) {
      this.getHt();
    },
    handleGmrqChange(val) {
      const currentTime = this.$dayjs();
      const startTime = this.$dayjs(val);
      this.form.synx = this.$dayjs.duration(currentTime.diff(startTime)).years();
    },
    handleAutoComplete(val) {
      const current = this.wpDic.find(item => item.id === val);
      this.form.pp = current.pp;
      this.form.ggxh = current.ggxh;
      this.form.ccrq = current.ccrq;
      this.form.gmrq = current.gmrq;
      this.handleGmrqChange(this.form.gmrq);
    },
    getHt() {
      const params = {
        cfd: this.form.cfd,
        fjh: this.form.fjh,
      };
      this.tableLoading = true;
      getAssetsHt(params).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          if (res.data) {
            this.form.krgs = res.data.krgs;
            this.form.krxm = res.data.krxm;
            this.form.fz = res.data.fz;
            this.form.htqx = res.data.htqx;
            this.form.htksrq = res.data.htksrq;
            this.form.htjsrq = res.data.htjsrq;
            this.form.dedd = res.data.dedd;
            this.htDisabe = true;
          } else {
            this.form.krgs = '';
            this.form.krxm = '';
            this.form.fz = '';
            this.form.htqx = '';
            this.form.htksrq = '';
            this.form.htjsrq = '';
            this.form.dedd = '';
            this.htDisabe = false;
          }
        }
      });
    },
    getZcDic() {
      const params = {
        page: 1,
        pageSize: 10000,
        description: '资产列表',
      };
      return getDicList(params);
    },
    getCfDic() {
      const params = {
        page: 1,
        pageSize: 10000,
        description: '存放地点-中介',
      };
      return getDicList(params);
    },
    getDdDic() {
      return findUserByRolecode({ rolecode: 'dandang' });
    },
    getWpDic() {
      return getAllList();
    },
  },
};
</script>

<style lang="scss" scoped>
.page {
  height: 100%;
  .el-card {
    height: 100%;
  }
}
.mc {
  width: 100px;
  float: left;
  text-overflow: ellipsis;
  overflow: hidden;
}
.pp {
  width: 100px;
  float: left;
  text-overflow: ellipsis;
  overflow: hidden;
  margin-left: 10px;
}
.gg {
  width: 150px;
  float: left;
  text-overflow: ellipsis;
  overflow: hidden;
  margin-left: 10px;
}
</style>
